﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Puddy.ViewModels;
using Puddy.Utils;
using Puddy.Models;
using System.Diagnostics;
using System.IO;
using Microsoft.Phone.BackgroundAudio;


namespace Puddy
{
    public partial class ToneSelectionPage : PhoneApplicationPage
    {

        public ToneSelectionPage()
        {
            InitializeComponent();
            DataContext = App.ViewModel.RingToneList;

            
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
            
        }

        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (App.RunningAlarm)
            {
                this.NavigationService.Navigate(new Uri("/AlarmPage.xaml", UriKind.Relative));
            }

            if (App.ShouldShowMessTurnOffLocation)
            {
                App.ShouldShowMessTurnOffLocation = false;
                MessageBox.Show(Constants.MES_TURN_OFF_LOCATION);

            }
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);

            BackgroundAudioPlayer.Instance.Stop();
        }

        protected async override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            await RestoreData.CreateJsonSetting(App.Setting);
        }

        private  void MainLongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If selected item is null (no selection) do nothing
            if (MainLongListSelector.SelectedItem == null)
                return;

            App.CurrentRingTone.IsSelected = false;

            App.CurrentRingTone = MainLongListSelector.SelectedItem as RingToneViewModel;
            App.Setting.AlarmTonePath = App.CurrentRingTone.Path;

            App.CurrentRingTone.IsSelected = true;


            AudioTrack audio = new AudioTrack(new Uri(App.CurrentRingTone.Name.Replace(" ", "")+".mp3", UriKind.Relative),
                             App.CurrentRingTone.Name,
                            "Windows Phone",
                            "",
                            null);

            BackgroundAudioPlayer.Instance.Track = audio;

            BackgroundAudioPlayer.Instance.Play();

            

            
        }

    }
}